// --------------------------------------------------------------
//      Star-XP Digitize Framework
//
// --------------------------------------------------------------

#include <vector>
#include <string>
#include <algorithm>
#include <regex>
#include <sys/stat.h>
#include <iostream>

#include "TSystem.h"
#include "TString.h"
#include "TEnv.h"

#include "YamlConfiger.hh"
#include "Digitization.hh"

void PrintUsage()
{
    std::cout << "****************************************************************" << std::endl;
    std::cout << "****************************************************************" << std::endl;
    std::cout << "******** Welcome to CEvNS-UCAS Digitization Framework! *********" << std::endl;
    std::cout << "******** Usage: ./Digitize [DigiCard.yml]              *********" << std::endl;
    std::cout << "****************************************************************" << std::endl;
    std::cout << "****************************************************************" << std::endl;
}

bool IfFileExist(std::string FilePath)
{
    struct stat buffer;   
    return (stat(FilePath.c_str(), &buffer) == 0);
}

std::vector<std::string> SplitStr(const char* Str, const char* Split)
{
    std::string VStr(Str);
    std::vector<std::string> Vector;
    std::regex Delimiter(Split);
    std::sregex_token_iterator iter(VStr.begin(), VStr.end(), Delimiter, -1);
    std::sregex_token_iterator end;
    while (iter != end)
    {   
        Vector.push_back(std::string(*iter));
        ++iter;
    }
    return Vector;
}

//main function
int main(int argc, char **argv)
{
    std::string InitCard = "DigiCard.yml";
    bool UseDefaultCard = true;
    // Add arglist control
    PrintUsage();
    if (argc >= 2)
    {
        for(int iA = 1; iA < argc; ++iA)
        {
           // if(std::string(argv[iA][0]) == std::string("-"))
           // {
           //     if(std::string(argv[iA]) == std::string("-v"))
           //     {
           //         std::cout << " Use interactive mode" << std::endl;
           //     }
           // }
            //else if(SplitStr(argv[iA], "\\.").back() == std::string("card"))
            if(SplitStr(argv[iA], "\\.").back() == std::string("yml"))
            {
                InitCard = std::string(argv[iA]);
                UseDefaultCard = false;
            }
        }
    }
    if(UseDefaultCard)
    {
        std::cout << "Warning!!! Using default " << InitCard << std::endl;
        if (!IfFileExist(InitCard))
        {
            std::cerr << "Error!!! Initialize card \" " << InitCard << " \" NOT FOUND!!!" << std::endl;
            return 1;
        }
    }

    //Load configer
    YamlConfiger* configer = YamlConfiger::GetInstance();
    configer->LoadConfiger(InitCard);

    Digitization digi;
    digi.Processing();
}
